package com.efuture.mutlithread;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassNAME ProcuderAndConsumer
 * @Description 演示生产者和消费者模式
 * @Author zhaoshanshan
 * @Date 2021/9/11 1:57 下午
 * @Version 1.0
 */
public class ProcuderAndConsumer {

    public static void main(String[] args) {
        List list = new ArrayList();//仓库
        ProcuderThread p = new ProcuderThread(list);
        p.setName("生产者线程");

        ConsumerThread c = new ConsumerThread(list);
        c.setName("消费者线程");
        p.start();
        c.start();
    }
}
//生产者线程
class ProcuderThread extends Thread{
    private List list;
    ProcuderThread(List list){
        this.list = list;
    }
    @Override
    public void run() {
       while (true){
           synchronized (list){
               if(list.size()>0){//仓库有货 不需要继续生产
                   try {
                       list.wait();//进入等待 释放锁，让消费者取消费
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               }
               //仓库没有货 需要生成
               Object o = new Object();
               list.add(o);
               System.out.println("生产了一件货物");
               list.notifyAll();//唤醒拥有list锁的线程 进行消费或者生产

           }
       }
    }
}
//消费者线程
class ConsumerThread extends Thread{
    private List list;
    ConsumerThread(List list){
        this.list = list;
    }
    @Override
    public void run() {
        while (true){
            synchronized (list){
                if(list.size()==0){//仓库没有货 需要等待生产者生产
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //仓库有货 进行消费
                list.remove(0);
                System.out.println("消费了一件货物");
                list.notifyAll();//唤醒拥有list锁的线程 进行消费或者生产
            }
        }
    }
}